package org.example.trainTicketSystem.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.trainTicketSystem.DTO.SaleRecordDTO;
import org.example.trainTicketSystem.entity.SaleRecord;
import org.example.trainTicketSystem.entity.Ticket;
import org.example.trainTicketSystem.entity.User;
import org.example.trainTicketSystem.service.SaleRecordService;
import org.example.trainTicketSystem.service.TicketService;
import org.example.trainTicketSystem.service.UserService;
import org.example.trainTicketSystem.utils.ResponseResult;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/api/sales")
@RequiredArgsConstructor
public class SaleRecordController {

    private final SaleRecordService saleRecordService;
    private final TicketService ticketService;
    private final UserService userService;

    @PostMapping()
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<SaleRecord> addSaleRecord(
            @Valid @RequestBody SaleRecordDTO saleRecordDTO,
            HttpServletRequest request) {

        // 获取当前登录用户
        Integer currentUserId = (Integer) request.getAttribute("userId");
        if (currentUserId == null) {
            log.warn("Unauthorized sale record creation attempt");
            return ResponseResult.fail("未登录用户无法购票");
        }

        try {
            // 验证用户是否存在
            User user = userService.getById(currentUserId);
            if (user == null) {
                log.warn("User not found: {}", currentUserId);
                return ResponseResult.fail("用户不存在");
            }

            // 验证车票
            Ticket ticket = ticketService.getById(saleRecordDTO.getTicketId());
            if (ticket == null) {
                log.warn("Ticket not found: {}", saleRecordDTO.getTicketId());
                return ResponseResult.fail("该车票不存在");
            }

            // 检查车票状态
            if (!"AVAILABLE".equalsIgnoreCase(ticket.getStatus()) && !"REFUNDED".equalsIgnoreCase(ticket.getStatus())) {
                log.warn("Ticket already sold or unavailable: {}", saleRecordDTO.getTicketId());
                return ResponseResult.fail("该票已售出或无法购买");
            }

            // 更新车票状态
            ticket.setStatus("SOLD");

            // 补充销售记录信息
            SaleRecord saleRecord = new SaleRecord(saleRecordDTO);
            saleRecord.setUserId(currentUserId);

            // 原子性操作：更新车票和保存销售记录
            boolean updateTicketResult = ticketService.updateById(ticket);
            boolean saveSaleRecordResult = saleRecordService.save(saleRecord);

            if (updateTicketResult && saveSaleRecordResult) {
                log.info("Ticket sold successfully: userId={}, ticketId={}",
                        currentUserId, saleRecordDTO.getTicketId());
                return ResponseResult.success("购买成功", saleRecord);
            } else {
                log.error("Failed to complete ticket sale: userId={}, ticketId={}",
                        currentUserId, saleRecordDTO.getTicketId());
                return ResponseResult.fail("购票失败，请稍后重试");
            }

        } catch (Exception e) {
            log.error("Error processing ticket sale", e);
            return ResponseResult.fail(e.getMessage());
        }
    }

    @GetMapping("/{userId}")
    public ResponseResult<Page<SaleRecord>> getSaleRecord(
            @PathVariable int userId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            HttpServletRequest request) {

        // 获取当前登录用户
        Integer currentUserId = (Integer) request.getAttribute("userId");

        // 权限检查：只能查询自己的记录，除非是管理员
        Boolean isAdmin = (Boolean) request.getAttribute("isAdmin");
        if (!currentUserId.equals(userId) && !Boolean.TRUE.equals(isAdmin)) {
            log.warn("Unauthorized sale record access: currentUser={}, requestedUser={}",
                    currentUserId, userId);
            return ResponseResult.fail("无权查看其他用户的销售记录");
        }

        // 规范化分页参数
        page = Math.max(1, page);
        size = Math.min(Math.max(1, size), 100);

        try {
            Page<SaleRecord> saleRecords = saleRecordService.getSaleRecordsByUserId(userId, page, size);

            if (saleRecords.getRecords().isEmpty()) {
                log.info("No sale records found for user: {}", userId);
                return ResponseResult.success("暂无售票记录", saleRecords);
            }

            log.info("Sale records retrieved successfully: userId={}, page={}, total={}",
                    userId, page, saleRecords.getTotal());
            return ResponseResult.success("售票记录查找成功", saleRecords);

        } catch (Exception e) {
            log.error("Error retrieving sale records", e);
            return ResponseResult.fail("获取售票记录失败");
        }
    }
}